package com.heima.comment.service.impl;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.ApCommentRepayVO;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.*;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    GreenScan greenScan;

    @Autowired
    UserFeign userFeign;

    /**
     * 查看更多回复内容
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        Integer size = dto.getSize();
        if(size == null){
            size = 10;
        }
        //按条件查询评论回复列表
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(size);
        List<ApCommentRepay> repayList = mongoTemplate.find(query, ApCommentRepay.class);
        //检查用户是否登录 如果未登录 直接返回列表
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.okResult(repayList);
        }
        // 如果登录 查询用户给哪些回复点过赞
        List<ApCommentRepayVO> list = new ArrayList<>();
        for (ApCommentRepay repay : repayList) {
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(repay,apCommentRepayVO);
            //根据当前用户信息 查询列表 是否有对应的信息
            // 查询点赞表中 根据 评论回复中的id 查询
            Query query1 = Query.query(Criteria.where("commentRepayId").is(apCommentRepayVO.getId())
                    .and("authorId").is(repay.getAuthorId()));
            ApCommentRepayLike one = mongoTemplate.findOne(query1, ApCommentRepayLike.class);
                if(one != null){
                    apCommentRepayVO.setOperation((short)0);
                }
            list.add(apCommentRepayVO);
        }
        return ResponseResult.okResult(list);
    }

    /**
     * 保存回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //检查用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }

        // 获取评论内容
        String content = dto.getContent();
        //阿里云校验 评论内容是否违规
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block":
                    //获取到违规信息 替换为 原评论内容
                    String filteredContent = scanResult.getFilteredContent();
                    if(filteredContent != null){
                        content = filteredContent ;
                    }
                    break;
                case "review":
                    break;
                case "pass":
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //根据评论id 查询 评论信息 检查是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()).and("authorId").is(user.getId()));
        ApComment one = mongoTemplate.findOne(query, ApComment.class);
        // 远程调用获取 当前登录用户信息
        ResponseResult<ApUser> responseResult = userFeign.findUserById(user.getId());
        if(!responseResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApUser apUser = responseResult.getData();
        if(one == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //保存 评论回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(content);
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        //修改评论信息中 回复数量+1
        Update update = new Update();
        update.set("reply",one.getReply() + 1);
        mongoTemplate.updateMulti(query,update,ApComment.class);
        return ResponseResult.okResult();
    }

    /**
     * 点赞回复的评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //校验回复信息是否存在
        // 根据回复id 查询对应的回复信息
        Query query = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
        ApCommentRepay one = mongoTemplate.findOne(query, ApCommentRepay.class);
        if(one == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断 是点赞 还是 取消点赞
        // 返回 最新的点赞数量
        Map<String,Object> map = new HashMap<>();
        if(dto.getOperation().equals((short)0)){
            //为点赞操作
            //查询 是否已经点赞过
            Query  apCommentRepayLikeQuery = Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentRepayId").is(dto.getCommentRepayId()));
            ApCommentRepayLike templateOne = mongoTemplate.findOne(apCommentRepayLikeQuery, ApCommentRepayLike.class);
            if(templateOne != null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"你已经点赞过了 不能再点");
            }
            //说明没有点赞过 允许点赞
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short)0);
            mongoTemplate.save(apCommentRepayLike);
            //修改 回复信息的点赞数量
            Update update = new Update();
            update.set("likes",one.getLikes() +1);
            map.put("likes",one.getLikes()+1);
            mongoTemplate.updateMulti(query,update,ApCommentRepay.class);
        }else if(dto.getOperation().equals((short)1)){
            //取消点赞 删除对应的点赞信息  修改 回复的点赞数量
            Query  apCommentRepayLikeQuery = Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentRepayId").is(dto.getCommentRepayId()));
            mongoTemplate.remove(apCommentRepayLikeQuery,ApCommentRepayLike.class);
            Update update = new Update();
            if(one.getLikes() >=1){
                update.set("likes",one.getLikes() -1);
                mongoTemplate.updateMulti(query,update,ApCommentRepay.class);
                map.put("likes",one.getLikes()-1);
            }
        }
        return ResponseResult.okResult(map);
    }
}
